#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
前端服务启动脚本
用于独立启动前端静态文件服务器
"""

import http.server
import socketserver
import os
import sys
import webbrowser
import threading
import time
from pathlib import Path

# 配置
PORT = 3000
DIRECTORY = Path(__file__).parent / "frontend"

class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    """自定义HTTP请求处理器"""
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=str(DIRECTORY), **kwargs)
    
    def end_headers(self):
        # 添加CORS头，允许跨域请求
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        super().end_headers()
    
    def log_message(self, format, *args):
        """自定义日志格式"""
        sys.stdout.write("%s - [%s] %s\n" %
                         (self.address_string(),
                          self.log_date_time_string(),
                          format % args))

def open_browser():
    """延迟打开浏览器"""
    time.sleep(1.5)  # 等待服务器完全启动
    webbrowser.open(f'http://localhost:{PORT}')

def start_server():
    """启动前端服务器"""
    try:
        with socketserver.TCPServer(("", PORT), CustomHTTPRequestHandler) as httpd:
            print("=" * 60)
            print("🚀 前端服务器启动成功！")
            print("=" * 60)
            print(f"📁 服务目录: {DIRECTORY}")
            print(f"🌐 访问地址: http://localhost:{PORT}")
            print(f"🌐 访问地址: http://127.0.0.1:{PORT}")
            print("=" * 60)
            print("💡 提示: 请确保后端服务已在 http://localhost:8000 运行")
            print("=" * 60)
            print("\n⏳ 正在打开浏览器...")
            print("按 Ctrl+C 停止服务器\n")
            
            # 在后台线程中打开浏览器
            browser_thread = threading.Thread(target=open_browser)
            browser_thread.daemon = True
            browser_thread.start()
            
            httpd.serve_forever()
    except KeyboardInterrupt:
        print("\n\n👋 前端服务器已停止")
    except OSError as e:
        if e.errno == 10048:
            print(f"\n❌ 错误: 端口 {PORT} 已被占用，请修改PORT变量或关闭占用该端口的程序")
        else:
            print(f"\n❌ 错误: {e}")
        sys.exit(1)

if __name__ == "__main__":
    start_server()
